/**
 * FormItem.java
 * Copyright (C) 2009 Jose Mauro da Silva Sandy
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 *  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 * FormItem.java
 *
 * Created on 09/05/2009, 23:52:07
 */

package frames;
import java.io.File;
import java.io.IOException;
import java.text.*;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import negocio.notas.*;
import negocio.produto.Produto;
import utils.*;

/**
 *
 * @author jmsandy
 */
public class FormItem extends javax.swing.JDialog {

    //<editor-fold defaultstate="collapsed" desc="FIELDS">
    private String idObj         = null;
    private ArrayList lstObj     = null;
    private int formulario       = 0;
    private int situacao         = 0;
    private double valorApurado  = 0;
    private double valorRecebido = 0;
    DecimalFormat df             = new DecimalFormat("#,##0.00");
    private boolean insert       = false;
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Constants">
    public static final int K_FORM_NOTA      = 1;
    public static final int K_FORM_ORCAMENTO = 2;
    public static final int K_FORM_EXIBICAO  = 3;
    public static final int K_FORM_CADASTRO  = 4;
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Acessores">
    public boolean getInserted(){
        return insert;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Constructors">
    /** Creates new form FormItem */
    public FormItem() {
        initComponents();
    }
    public FormItem(Integer tipo, Integer formulario, String idObj, 
                    Double val){
        initComponents();
        this.situacao = tipo == K_FORM_EXIBICAO ?
                                        FormItemInclude.K_FORM_EXIBICAO :
                                        FormItemInclude.K_FORM_CADASTRO;
        this.formulario = formulario == K_FORM_ORCAMENTO ?
                                        FormItemInclude.K_FORM_ORCAMENTO :
                                        FormItemInclude.K_FORM_NOTA;
        this.idObj = idObj;
        this.valorRecebido = val;
        initializeMyComponents();
    }
    //</editor-fold>

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FormItem().setVisible(true);
            }
        });
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        tableItem = new javax.swing.JTable();
        panelBotao = new javax.swing.JPanel();
        btnIncluir = new javax.swing.JButton();
        btnEditar = new javax.swing.JButton();
        btnExcluir = new javax.swing.JButton();
        btnAnterior = new javax.swing.JButton();
        btnProximo = new javax.swing.JButton();
        panel = new javax.swing.JPanel();
        lbInformado = new javax.swing.JLabel();
        lbDiferenca = new javax.swing.JLabel();
        lbValorApurado = new javax.swing.JLabel();
        textValorInformado = new javax.swing.JTextField();
        textDiferenca = new javax.swing.JTextField();
        textValorApurado = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Item");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setName("formItem"); // NOI18N
        setResizable(false);

        tableItem.setFont(new java.awt.Font("SansSerif", 0, 12));
        tableItem.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código", "Descrição", "Quantidade", "Unidade", "Conversão", "Valor Unitário", "Valor Total"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tableItem);

        panelBotao.setBorder(javax.swing.BorderFactory.createEtchedBorder(null, java.awt.Color.gray));
        panelBotao.setFont(new java.awt.Font("DejaVu Sans", 0, 12));

        btnIncluir.setFont(new java.awt.Font("SansSerif", 0, 12)); // NOI18N
        btnIncluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/add.png"))); // NOI18N
        btnIncluir.setText("Incluir");
        btnIncluir.setToolTipText("Incluir Item");
        btnIncluir.setEnabled(false);
        btnIncluir.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnIncluirMouseClicked(evt);
            }
        });

        btnEditar.setFont(new java.awt.Font("SansSerif", 0, 12)); // NOI18N
        btnEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/editItem.png"))); // NOI18N
        btnEditar.setText("Editar");
        btnEditar.setToolTipText("Editar Item");
        btnEditar.setEnabled(false);
        btnEditar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnEditarMouseClicked(evt);
            }
        });

        btnExcluir.setFont(new java.awt.Font("SansSerif", 0, 12)); // NOI18N
        btnExcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.png"))); // NOI18N
        btnExcluir.setText("Excluir");
        btnExcluir.setToolTipText("Excluir Item");
        btnExcluir.setEnabled(false);
        btnExcluir.setMaximumSize(new java.awt.Dimension(92, 34));
        btnExcluir.setMinimumSize(new java.awt.Dimension(92, 34));
        btnExcluir.setPreferredSize(new java.awt.Dimension(92, 34));
        btnExcluir.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnExcluirMouseClicked(evt);
            }
        });

        btnAnterior.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnAnterior.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/previous.png"))); // NOI18N
        btnAnterior.setToolTipText("Anterior");
        btnAnterior.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnAnteriorMouseClicked(evt);
            }
        });

        btnProximo.setFont(new java.awt.Font("SansSerif", 0, 12));
        btnProximo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/next.png"))); // NOI18N
        btnProximo.setToolTipText("Próximo");
        btnProximo.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnProximoMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout panelBotaoLayout = new javax.swing.GroupLayout(panelBotao);
        panelBotao.setLayout(panelBotaoLayout);
        panelBotaoLayout.setHorizontalGroup(
            panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelBotaoLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelBotaoLayout.createSequentialGroup()
                        .addComponent(btnAnterior, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnProximo, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(10, 10, 10))
                    .addComponent(btnEditar, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
                    .addComponent(btnIncluir, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
                    .addComponent(btnExcluir, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE))
                .addContainerGap())
        );
        panelBotaoLayout.setVerticalGroup(
            panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelBotaoLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnIncluir)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnEditar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 142, Short.MAX_VALUE)
                .addGroup(panelBotaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnProximo)
                    .addComponent(btnAnterior))
                .addContainerGap())
        );

        panelBotaoLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnEditar, btnExcluir, btnIncluir});

        panel.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        lbInformado.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbInformado.setText("Valor Informado");

        lbDiferenca.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbDiferenca.setText("Diferença");

        lbValorApurado.setFont(new java.awt.Font("SansSerif", 0, 12));
        lbValorApurado.setText("Valor Apurado");

        textValorInformado.setBackground(java.awt.Color.white);
        textValorInformado.setEditable(false);
        textValorInformado.setFont(new java.awt.Font("SansSerif", 0, 12));
        textValorInformado.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        textValorInformado.setPreferredSize(new java.awt.Dimension(10, 26));

        textDiferenca.setBackground(java.awt.Color.white);
        textDiferenca.setEditable(false);
        textDiferenca.setFont(new java.awt.Font("SansSerif", 0, 12));
        textDiferenca.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        textDiferenca.setPreferredSize(new java.awt.Dimension(10, 26));

        textValorApurado.setBackground(java.awt.Color.white);
        textValorApurado.setEditable(false);
        textValorApurado.setFont(new java.awt.Font("SansSerif", 0, 12));
        textValorApurado.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        textValorApurado.setPreferredSize(new java.awt.Dimension(10, 26));

        javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel);
        panel.setLayout(panelLayout);
        panelLayout.setHorizontalGroup(
            panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelLayout.createSequentialGroup()
                .addContainerGap(416, Short.MAX_VALUE)
                .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(panelLayout.createSequentialGroup()
                        .addComponent(lbDiferenca)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(textDiferenca, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(panelLayout.createSequentialGroup()
                        .addComponent(lbInformado)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(textValorInformado, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(panelLayout.createSequentialGroup()
                        .addComponent(lbValorApurado)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(textValorApurado, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        panelLayout.setVerticalGroup(
            panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbInformado)
                    .addComponent(textValorInformado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbDiferenca)
                    .addComponent(textDiferenca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbValorApurado)
                    .addComponent(textValorApurado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(panel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 668, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(panelBotao, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(panelBotao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-855)/2, (screenSize.height-371)/2, 855, 371);
    }// </editor-fold>//GEN-END:initComponents

    //<editor-fold defaultstate="collapsed" desc="Events">
    // Oculta voltando para o formulario anterior
    private void btnAnteriorMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnAnteriorMouseClicked
        this.setVisible(false);
    }//GEN-LAST:event_btnAnteriorMouseClicked

    // Inclui um item ao formulario
    private void btnIncluirMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnIncluirMouseClicked
        // Verifica se o botao de inclusao esta em estado de edicao
        if(btnIncluir.isEnabled()){
            Item item = new Item();
            this.setFocusable(false);
            FormItemInclude form;

            // De acodo com o a chamada a propriedade e setada para o item
            if(formulario == K_FORM_ORCAMENTO){
                item.setIdOrcamento(idObj);
            }
            else{
                item.setIdNota(idObj);
            }

            form = new FormItemInclude(item, formulario, situacao);
            // Realiza a chamada para inclusao do item            
            form.setModal(true);
            form.setVisible(true);
            this.setFocusable(true);
            if(item != null){
                DefaultTableModel dtm = (DefaultTableModel)tableItem.getModel();
                insertTable(item, dtm);
                lstObj.add(item);
                showFields();
                enableFields();
            }
       }
    }//GEN-LAST:event_btnIncluirMouseClicked

    // Remove um item do formulario
    private void btnExcluirMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnExcluirMouseClicked
        // Verifica se o botao esta habilitado
        try{
            if(btnExcluir.isEnabled()){
                // Recebe o registro selecionado no grid
                int index = tableItem.getSelectedRow();

                // Caso tenha sido selecionado algum registro o mesmo e removido
                if(index > -1){
                    Item it = new Item();
                    it = (Item) lstObj.get(index);

                    if(it.delete()){
                        lstObj.remove(it);
                        DefaultTableModel dtm =
                                        (DefaultTableModel)tableItem.getModel();
                        removeItemTable(index, it, dtm);
                        showFields();
                        enableFields();
                    }
                }
            }
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
    }//GEN-LAST:event_btnExcluirMouseClicked

    // Edita um registro do formulario
    private void btnEditarMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnEditarMouseClicked
        // Verifica se o botao esta habilitado
        try{
            if(btnEditar.isEnabled()){
                // Recebe o registro selecionado no grid
                int index = tableItem.getSelectedRow();

                // Caso tenha sido selecionado algum registro o mesmo e removido
                if(index > -1){

                    Item item = new Item();
                    item = (Item) lstObj.get(index);
                    Double val =
                            item.getQuantidade() * item.getValorUnitario();

                    // Realiza a chamada para inclusao do item
                    FormItemInclude form;
                    form = new FormItemInclude(item, formulario, situacao);
                    form.setModal(true);
                    form.setVisible(true);
                    this.setFocusable(true);

                    if(this.situacao != K_FORM_EXIBICAO){
                        // Recebe o valor anterior as mudancas

                        if(item != null){
                            DefaultTableModel dtm =
                                        (DefaultTableModel)tableItem.getModel();
                            val = item.getQuantidade() *
                                                  item.getValorUnitario() - val;
                            updateItemTable(index, item, dtm, val);
                            showFields();
                            enableFields();
                        }
                    }
                }               
            }
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
    }//GEN-LAST:event_btnEditarMouseClicked

    // Avanca para o proximo formulario
    private void btnProximoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnProximoMouseClicked

        try{
            // Verifica se existe diferenca entre os valores apurado e recebido
            if(valorApurado == valorRecebido){
                // Verifica qual sera o acao a ser tomada
                if(formulario == K_FORM_ORCAMENTO){
                    Orcamento orc = new Orcamento();
                    orc = orc.refresh(idObj);
                    if(orc.getSituacao() != StatusOrcamento.CONFIRMADO){
                        orc.setSituacao(StatusOrcamento.ABERTO);

                        // Atualiza o orcamento corrente
                        if(orc.update()){
                            showMessageInformation(
                                        ErrorMessage.MSG_ORCAMENTO_INSERCAO,
                                        "Orçamento");
                            insert = true;
                            dispose();
                        }
                        else{
                            showMessageError(ErrorMessage.MSG_GERAL_BANCO,
                                             "Orçamento");
                        }
                    }
                    else{
                        dispose();
                    }
                }
                else{
                    if(situacao == K_FORM_EXIBICAO){
                        showFormContas(FormContas.K_FORM_EXIBICAO);
                    }
                    else{
                        showFormContas(FormContas.K_FORM_CADASTRO);
                    }
                }
            }
            else{
                showMessageError(ErrorMessage.MSG_GERAL_VALOR, "Erro");
            }
        }
        catch(Exception ex){}
    }//GEN-LAST:event_btnProximoMouseClicked
    //</editor-fold>

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAnterior;
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnExcluir;
    private javax.swing.JButton btnIncluir;
    private javax.swing.JButton btnProximo;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lbDiferenca;
    private javax.swing.JLabel lbInformado;
    private javax.swing.JLabel lbValorApurado;
    private javax.swing.JPanel panel;
    private javax.swing.JPanel panelBotao;
    private javax.swing.JTable tableItem;
    private javax.swing.JTextField textDiferenca;
    private javax.swing.JTextField textValorApurado;
    private javax.swing.JTextField textValorInformado;
    // End of variables declaration//GEN-END:variables

    //<editor-fold defaultstate="collapsed" desc="Methods">
    private void showFormContas(int tipo){
        Nota nota = (new Nota()).refresh(idObj);
        FormContas form = new FormContas(tipo, nota.getCod_objeto(),
                               nota.getEmpreendimento(), nota.getValorNota());
        form.setModal(true);
        form.setVisible(true);

        if(form.getInserted()){
            nota.setSituacao(StatusNota.CONFIRMADO);
            insert = true;
            form.dispose();
            atualizLstProdutos();
            dispose();
        }
        else{
            form.dispose();
        }
    }

    private void showMessageError(String msg, String title){
        JOptionPane.showMessageDialog(this, msg, title,
                                                    JOptionPane.ERROR_MESSAGE);
    }

    // Messagem de alerta
    private void showMessageInformation(String msg, String title){
        JOptionPane.showMessageDialog(this, msg, title,
                                               JOptionPane.INFORMATION_MESSAGE);
    }

    // Inicializa as colunas padroes da tabela
    private void initializeTable(){
        tableItem.getColumnModel().getColumn(0).setPreferredWidth(50);
        tableItem.getColumnModel().getColumn(0).setResizable(false);
        tableItem.getColumnModel().getColumn(1).setPreferredWidth(246);
        tableItem.getColumnModel().getColumn(1).setResizable(false);
        tableItem.getColumnModel().getColumn(2).setPreferredWidth(76);
        tableItem.getColumnModel().getColumn(2).setResizable(false);
        tableItem.getColumnModel().getColumn(2).setCellRenderer(
                                            Auxiliar.getAlign(Auxiliar.RIGHT));
        tableItem.getColumnModel().getColumn(3).setPreferredWidth(56);
        tableItem.getColumnModel().getColumn(3).setResizable(false);
        tableItem.getColumnModel().getColumn(3).setCellRenderer(
                                            Auxiliar.getAlign(Auxiliar.RIGHT));
        tableItem.getColumnModel().getColumn(4).setPreferredWidth(76);
        tableItem.getColumnModel().getColumn(4).setResizable(false);
        tableItem.getColumnModel().getColumn(4).setCellRenderer(
                                            Auxiliar.getAlign(Auxiliar.RIGHT));
        tableItem.getColumnModel().getColumn(5).setPreferredWidth(86);
        tableItem.getColumnModel().getColumn(5).setResizable(false);
        tableItem.getColumnModel().getColumn(5).setCellRenderer(
                                            Auxiliar.getAlign(Auxiliar.RIGHT));
        tableItem.getColumnModel().getColumn(6).setPreferredWidth(76);
        tableItem.getColumnModel().getColumn(6).setResizable(false);
        tableItem.getColumnModel().getColumn(6).setCellRenderer(
                                            Auxiliar.getAlign(Auxiliar.RIGHT));

        tableItem.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        tableItem.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    // Inicializa o estados de todos os botoes
    private void initializeMyComponents(){
        // Levando em consideracao a situacao recebida e realizada uma
        // busca para obtencao da lista de objetos
        lstObj = new ArrayList();
        Item item = new Item();

        if(this.formulario == K_FORM_ORCAMENTO){
            lstObj = item.recLstItens(idObj, Item.K_ITEM_ORCAMENTO);
        }
        else{
            lstObj = item.recLstItens(idObj, Item.K_ITEM_NOTA);
        }

        initializeTable();
        populateTable();
        showFields();

        if(this.situacao == K_FORM_EXIBICAO){
            alterButton();
            insert = true;
        }
        else{
            insert = false;
            enableFields();
        }
    }

    // Apresenta os campos na tabela
    private void populateTable(){
        DefaultTableModel dtm = (DefaultTableModel)tableItem.getModel();
        tableItem.removeAll();
        tableItem.updateUI();

        // Percorre a extensao da lista para adicionar na tabela os registros
        // existentes
        for(Item item : (ArrayList<Item>)lstObj){
            insertTable(item, dtm);
        }
    }

    // Apresenta os valores nos edits
    private void showFields(){
        textValorInformado.setText(formatDouble(valorRecebido));
        textValorApurado.setText(formatDouble(valorApurado));
        textDiferenca.setText(formatDouble(valorRecebido - valorApurado));
    }

    // Habilita os botoes para edicao
    private void enableFields(){
        if(tableItem.getRowCount() > 0){
            btnExcluir.setEnabled(true); btnEditar.setEnabled(true);
        }
        else{
            btnExcluir.setEnabled(false); btnEditar.setEnabled(false);
        }

        if(valorApurado < valorRecebido){
            btnIncluir.setEnabled(true);
        }
        else{
            btnIncluir.setEnabled(false);
        }
    }

    // Insere um item na tabela
    private void insertTable(Item item, DefaultTableModel dtm){
        // Recupera o produto vinculado ao item para exibicao
        Produto prod = new Produto();
        prod = prod.refresh(item.getIdProduto());
        double val = item.getQuantidade() * item.getValorUnitario();
        valorApurado += val;

        Object[] row = new Object[]{prod.getCodProd(), prod.getDescricao(),
                       formatDouble(item.getQuantidade()), item.getUnidCompra(),
                       formatDouble(item.getFatorConv()),
                       "R$ " + formatDouble(item.getValorUnitario()),
                       "R$ " + formatDouble(val)};
        dtm.addRow(row);
    }

    // Remove um item da tabela de itens
    private void removeItemTable(int index, Item item, DefaultTableModel dtm){
        dtm.removeRow(index);
        tableItem.updateUI();

        valorApurado -= item.getQuantidade() * item.getValorUnitario();
    }

    // Atualiza um item da tabela de itens
    private void updateItemTable(int index, Item item,
                                DefaultTableModel dtm, Double valMod){
        // Recupera o produto vinculado ao item para exibicao
        Produto prod = new Produto();
        prod = prod.refresh(item.getIdProduto());
        Double val = item.getQuantidade() * item.getValorUnitario();
        valorApurado += valMod;
        
        dtm.setValueAt(prod.getCodProd(), index, 0);
        dtm.setValueAt(prod.getDescricao(), index, 1);
        dtm.setValueAt(formatDouble(item.getQuantidade()), index, 2);
        dtm.setValueAt(item.getUnidCompra(), index, 3);
        dtm.setValueAt(formatDouble(item.getFatorConv()), index, 4);
        dtm.setValueAt("R$ " + formatDouble(item.getValorUnitario()), index, 5);
        dtm.setValueAt("R$ " + formatDouble(val), index, 6);
    }

    // Formata um double para apresentacao
    private String formatDouble(Double val){
        return df.format(val).replace(",", ".");
    }

    // Altera o status do botao
    private void alterButton(){
        try{
            String path = new File(".").getCanonicalPath() + Auxiliar.getTokenSO()
                          + "images" + Auxiliar.getTokenSO();
            btnEditar.setText("Consultar");
            btnEditar.setEnabled(true);
            btnEditar.setIcon(new ImageIcon(path + "lupa.png"));
        }
        catch(Exception ex){}
    }

    // Atualiza a lista de itens que fora inserido
    private void atualizLstProdutos(){
        // Responsavel por pegar a data que sera atualizada
        Nota nota = (new Nota()).refresh(idObj);
        ArrayList<Produto> lstProdutos = new ArrayList<Produto>();

        /**
         * Percorre a lista dos itens que acabara de ser inseridos para uma
         * dada nota e atualiza toda as suas informacoes de compra
         */
        for(Item item : (ArrayList<Item>)lstObj){
            Produto prod = (new Produto()).refresh(item.getIdProduto());

            double menorPreco = (prod.getMenorPreco() <= item.getValorUnitario()
                                                    && prod.getMenorPreco() != 0)?
                                prod.getMenorPreco() : item.getValorUnitario();

            prod.setDataUltCompra(nota.getDtEntrada());
            prod.setPrecoUltCompra(item.getValorUnitario());
            prod.setMenorPreco(menorPreco);

            lstProdutos.add(prod);
        }

        try{
            (new Produto()).atualizLista(lstProdutos);
        }
        catch(IOException ex){}
    }
    //</editor-fold>
}
